package com.mystnihon.models;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FtpManager {

	private Map<String, FtpClientThread> listdownload = new HashMap<String, FtpClientThread>();

	public void download(String filename) {
		try {
			File file = new File(filename);
			if (file.exists()) {

			} else {
				if (listdownload.containsKey(filename)) {

				} else {
					FtpClientThread client = new FtpClientThread();
					listdownload.put(filename, client);
					client.download(filename, file,
							new FTPDataTransferListener() {

								@Override
								public void aborted() {
									// TODO Auto-generated method stub

								}

								@Override
								public void completed() {
									// TODO Auto-generated method stub

								}

								@Override
								public void failed() {
									// TODO Auto-generated method stub

								}

								@Override
								public void started() {
									// TODO Auto-generated method stub

								}

								@Override
								public void transferred(int arg0) {
									// TODO Auto-generated method stub

								}

							});
				}

			}
		} catch (Exception e) {
		}
	}

	public class FtpClientThread extends FTPClient implements Runnable {

		private static final int THREAD_SLEEP = 200;
		protected volatile boolean run = true;

		@Override
		public void run() {
			// TODO Auto-generated method stub

			while (run) {
				try {
					Thread.sleep(THREAD_SLEEP);
					System.out.println("Sleep");
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					break;
				}
			}
		}

		public synchronized void stop() {
			run = false;
		}

		public String[] connect(String url, int port)
				throws IllegalStateException, IOException,
				FTPIllegalReplyException, FTPException {
			new Thread(this).start();
			return super.connect(url, port);

		}

		public void disconnect(boolean nicely) throws IllegalStateException,
				IOException, FTPIllegalReplyException, FTPException {
			try {
				super.disconnect(nicely);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				throw e;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				throw e;
			} catch (FTPIllegalReplyException e) {
				// TODO Auto-generated catch block
				throw e;
			} catch (FTPException e) {
				// TODO Auto-generated catch block
				throw e;
			} finally {
				stop();
			}

		}

	}
}
